<?php

class UeditorWidget extends CWidget{

	public $id;
	public $options = array();
	/**
	 * Initializes the widget.
	 */
	public function init()
	{
		// Prevents the extension from registering scripts and publishing assets when ran from the command line.
		if (Yii::app() instanceof CConsoleApplication)
			return;

		/** @var CClientScript $cs */
		$cs = Yii::app()->getClientScript();
		$cs->registerScriptFile($this->getAssetsUrl().'/ueditor.config.js',CClientScript::POS_END);
		$cs->registerScriptFile($this->assetsUrl.'/ueditor.all.min.js', CClientScript::POS_END);
	}


	/**
	 * Runs the widget.
	 */
	public function run()
	{
		$script = ' UE.getEditor("'.$this->id.'",{'.$this->renderOptions().'});';
		/** @var CClientScript $cs */
		$cs = Yii::app()->getClientScript();
		$cs->registerScript($this->id, $script);
	}

	/**
	 * Renders the items.
	 * @param array $items the item configuration.
	 */
	protected function renderOptions()
	{
		$script = '';
		foreach ($this->options as $key => $item)
		{
			if(is_array($item))
			{
				$script = $script."'$key':[";
				foreach ($item as $value)
					$script = $script."'$value',";
				$script = $script."],";
			} else
				$script = $script."'$key':'$item',";
		}
		return $script;
	}

	public function getAssetsUrl()
	{
		$assetsPath = Yii::getPathOfAlias('ext.ueditor.assets');
		$assetsUrl = Yii::app()->assetManager->publish($assetsPath, false, -1, YII_DEBUG);
		return $assetsUrl;
	}
	

}

?>